package com.poisonh.unifiedauth.utils;

import android.app.Activity;

import java.util.List;
import java.util.Stack;

/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 * * Created by PoisonH on 2016/8/5.
 */

public class ActivityStack
{
    private static Stack<Activity> activityStack;
    private static ActivityStack instance;

    private ActivityStack()
    {
        if (activityStack == null)
        {
            activityStack = new Stack<>();
        }
    }

    /**
     * 单一实例
     */
    public static ActivityStack getAppManager()
    {
        if (instance == null)
        {
            instance = new ActivityStack();
        }

        return instance;
    }

    /**
     * 获取指定的Activity
     *
     * @author kymjs
     */
    public static Activity getActivity(Class<?> cls)
    {
        if (activityStack != null)
            for (Activity activity : activityStack)
            {
                if (activity.getClass().equals(cls))
                {
                    return activity;
                }
            }
        return null;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity)
    {
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity()
    {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity()
    {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity)
    {
        if (activity != null && activityStack.contains(activity))
        {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    /**
     * 结束指定的Activity
     */
    public void removeActivity(Activity activity)
    {
        if (activity != null && activityStack.contains(activity))
        {
            activityStack.remove(activity);
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls)
    {
        for (Activity activity : activityStack)
        {
            if (activity.getClass().equals(cls))
            {
                finishActivity(activity);
                break;
            }
        }
    }

    /**
     * 退出应用程序
     */
    public void exit()
    {
        List<Activity> activities = ActivityStack.getAppManager().activityStack;
        for (Activity act : activities)
        {
            act.finish();// 显式结束
        }
        activityStack.clear();
    }

}